package top.wanzc.java.basic.design.pattern.singleton;

public class Singleton {
	
	private Singleton() {
		
	}
	
	private static Singleton instance1 = new Singleton(); // 急切加載也成爲餓漢模式
	
	public static Singleton getInstance1() {
		return instance1;
	}
	
	private static Singleton instance2;  // 加鎖延遲加載性能較低
	
	public synchronized static Singleton getInstance2() {
		if (instance2 == null) {
			return instance2 = new Singleton();
		}
		return instance2;
	}
	
	private volatile static Singleton instance3; //雙重枷鎖檢查不推薦
	
	public static Singleton getInstance3() {
		if (instance3 == null) {
			synchronized(Singleton.class) {
				if (instance3 == null) {
					instance3 = new Singleton();
				}
			}
		}
		return instance3;
	}
	
	private static class SingletonHolder {
		private static final Singleton instance = new Singleton(); // Holder模式，最爲推薦
	}
	
	public static Singleton getInstance() {
		return SingletonHolder.instance;
	}

}
